﻿using machine_registration.Infrastructure;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace machine_registration.Helpers
{
    public class SqlDataService : IDataService
    {
        private readonly AppDbContext _context;

        // 构造函数注入数据库上下文 
        public SqlDataService(AppDbContext context)
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
        }

        // 分页查询核心实现 
        public async Task<(List<BorrowRecord> Items, int TotalCount)> GetPagedRecordsAsync(
            int page = 1,
            int pageSize = 20,
            string keyword = null)
        {
            // 参数校验 
            if (page < 1) page = 1;
            if (pageSize < 1) pageSize = 20;

            // 构建基础查询 
            IQueryable<BorrowRecord> query = _context.BorrowRecords
                .AsNoTracking()  // 提升查询性能 
                .Include(r => r.DeviceName)  // 关联设备数据 
                .Include(r => r.Counterpart);  // 关联借阅人数据 

            // 动态添加过滤条件 
            if (!string.IsNullOrWhiteSpace(keyword))
            {
                string searchTerm = keyword.Trim().ToLower();
                query = query.Where(r =>
                    r.DeviceName.ToLower().Contains(searchTerm) ||
                    r.OwnerId.Contains(searchTerm) ||
                    r.Notes.Contains(searchTerm));
            }

            // 并行执行总记录数和分页查询 
            var totalTask = query.CountAsync();
            var dataTask = query
                .OrderByDescending(r => r.BorrowDate)  // 默认按借阅时间倒序 
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .ToListAsync();

            await Task.WhenAll(totalTask, dataTask);

            return (dataTask.Result, totalTask.Result);
        }

        // 删除记录实现 
        public async Task<bool> DeleteRecordAsync(string recordId)
        {
            var record = await _context.BorrowRecords
                .FirstOrDefaultAsync(r => r.Uuid == recordId);

            if (record == null) return false;

            try
            {
                _context.BorrowRecords.Remove(record);
                return await _context.SaveChangesAsync() > 0;
            }
            catch (DbUpdateException)
            {
                // 日志记录异常 
                return false;
            }
        }
    }
}
